﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using StockUtil;

namespace StockLib.Data
{
    public class XdrFileLoader
    {
        public virtual List<XdrData> Load(Stock stock)
        {
            List<XdrData> xdrData = new List<XdrData>();

            FileInfo fi = new FileInfo(StockData.Instance.GetFileName(stock, DataType.XDR));
            if (!fi.Exists)
                return xdrData;

            FileStream fs = null;
            int packSize = 0;
            int byteNumber = 0;
            byte[] buffer = null;

            try
            {
                fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);

                packSize = Marshal.SizeOf(typeof(XdrFilePack));
                buffer = new byte[packSize * 500];
                byteNumber = 0;
                while ((byteNumber = fs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    for (int i = 0; i < byteNumber / packSize; i++)
                    {
                        XdrFilePack pack = (XdrFilePack)StructHelper.FromBytes(buffer, i * packSize, typeof(XdrFilePack));
                        XdrData data = XdrFilePack.ToInternal(ref pack);
                        xdrData.Add(data);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }

            return xdrData;
        }
    }
}
